/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.klikmee.sms.chat.web.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author makcro
 */
@Transactional
public abstract class AbstractDAO<T> {
	@PersistenceContext
	protected EntityManager entityManager = null;

	private Class<T> entityClass;

	public AbstractDAO(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Transactional
	public void create(T entity) {
		entityManager.persist(entity);
	}

	@Transactional
	public void edit(T entity) {
		entityManager.merge(entity);
	}

	@Transactional
	public void delete(T entity) {
		T entityForDeletiing = entityManager.merge(entity);
		entityManager.remove(entityForDeletiing);
	}

	public T find(Object id) {
		return entityManager.find(entityClass, id);
	}

	public List<T> findAll() {
		javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
		cq.select(cq.from(entityClass));
		return entityManager.createQuery(cq).getResultList();
	}
	
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
}
